package com.haike.pushjobs.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/dc")
@Slf4j
public class DataCenterController extends BaseController {

    @Autowired
    SqlSession sqlSession;


    @RequestMapping("list")
    public Object getData(@RequestParam Map<String, String> map) {
        try {
            String method = map.getOrDefault("m", "");

            if (map.containsKey("st_code") && !map.containsKey("bh")) {
                map.put("bh", map.get("st_code"));
            }
            if (map.containsKey("bh") && !map.containsKey("st_code")) {
                map.put("st_code", map.get("bh"));
            }

            //region in参数处理
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                if (StrUtil.isBlank(key)) {
                    continue;
                }

                String value = entry.getValue();
                if (value.contains("'")) {
                    throw new Exception("非法请求");
                }

                if (key.startsWith("in_")) {
                    if (!StrUtil.isBlank(value)) {
                        value = "'" + value.replace("'", "").replace(",", "','") + "'";
                        map.put(key, value);
                    }
                }
            }
            //endregion

            Page<Object> page = null;
            if (map.containsKey("pagesize") || map.containsKey("pageindex")) {
                page = PageHelper.startPage(MapUtil.getInt(map, "pageindex"), MapUtil.getInt(map, "pagesize"));
            }

            List<Map> list = sqlSession.selectList("Search." + method, map);

            Map<String, Object> res = new HashMap<>();
            if (page != null) {
                res.put("total", page.getTotal());
                long startRowIndex = page.getStartRow() + 1;
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).put("RN", startRowIndex + i);
                }
            }
            res.put("list", list);
            return success(res);
        } catch (Exception ex) {
            return error(ex.getMessage());
        }
    }

}
